#!/usr/bin/env python3
"""
图表样式配置

Times New Roman字体设置、LaTeX支持、统一样式
"""

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pathlib import Path
import platform
import warnings


class PlotStyle:
    """图表样式配置类"""
    
    # 字体大小
    FONT_SIZE_TITLE = 14
    FONT_SIZE_AXIS = 12
    FONT_SIZE_LEGEND = 11
    FONT_SIZE_LABEL = 10
    
    # 字体族
    FONT_FAMILY = 'Times New Roman'
    
    # 背景色
    BACKGROUND_COLOR = '#ffffff'
    GRID_COLOR = '#e0e0e0'
    GRID_ALPHA = 0.3
    
    def __init__(self):
        """初始化样式配置"""
        self.setup_fonts()
        self.setup_latex()
    
    def setup_fonts(self):
        """设置Times New Roman字体"""
        try:
            # Windows系统
            if platform.system() == 'Windows':
                # Times New Roman通常已安装
                font_paths = [
                    r'C:\Windows\Fonts\times.ttf',
                    r'C:\Windows\Fonts\timesbd.ttf',
                    r'C:\Windows\Fonts\timesi.ttf',
                ]
            else:
                # Linux/Mac系统
                font_paths = [
                    '/usr/share/fonts/truetype/times.ttf',
                    '/System/Library/Fonts/Supplemental/Times New Roman.ttf',
                ]
            
            # 检查字体是否可用
            available_fonts = [f.name for f in fm.fontManager.ttflist]
            if 'Times New Roman' not in available_fonts:
                # 尝试注册字体
                for font_path in font_paths:
                    if Path(font_path).exists():
                        try:
                            fm.fontManager.addfont(font_path)
                            break
                        except:
                            pass
            
            # 设置默认字体
            plt.rcParams['font.family'] = 'serif'
            plt.rcParams['font.serif'] = ['Times New Roman', 'Times', 'DejaVu Serif']
            plt.rcParams['mathtext.fontset'] = 'stix'  # 数学字体
            
        except Exception as e:
            warnings.warn(f"字体设置失败: {e}，使用默认字体")
    
    def setup_latex(self):
        """设置LaTeX渲染支持"""
        try:
            # 启用LaTeX渲染
            plt.rcParams['text.usetex'] = False  # 先设为False，避免依赖LaTeX安装
            
            # 使用matplotlib的数学文本渲染
            plt.rcParams['mathtext.default'] = 'regular'
            plt.rcParams['mathtext.fontset'] = 'stix'
            
        except Exception as e:
            warnings.warn(f"LaTeX设置失败: {e}，使用matplotlib数学文本")
    
    def apply_style(self):
        """应用统一样式"""
        # 字体设置
        plt.rcParams.update({
            'font.family': 'serif',
            'font.serif': ['Times New Roman', 'Times', 'DejaVu Serif'],
            'font.size': self.FONT_SIZE_AXIS,
            'axes.titlesize': self.FONT_SIZE_TITLE,
            'axes.labelsize': self.FONT_SIZE_AXIS,
            'xtick.labelsize': self.FONT_SIZE_LABEL,
            'ytick.labelsize': self.FONT_SIZE_LABEL,
            'legend.fontsize': self.FONT_SIZE_LEGEND,
            'figure.titlesize': self.FONT_SIZE_TITLE,
            
            # 数学字体
            'mathtext.fontset': 'stix',
            'mathtext.default': 'regular',
            
            # 背景和网格
            'figure.facecolor': self.BACKGROUND_COLOR,
            'axes.facecolor': self.BACKGROUND_COLOR,
            'axes.grid': True,
            'grid.color': self.GRID_COLOR,
            'grid.alpha': self.GRID_ALPHA,
            'grid.linewidth': 0.5,
            'grid.linestyle': '--',
            
            # 线条和边框
            'axes.linewidth': 0.8,
            'axes.spines.top': False,
            'axes.spines.right': False,
            
            # 图例
            'legend.frameon': True,
            'legend.framealpha': 0.9,
            'legend.fancybox': False,
            'legend.edgecolor': '#cccccc',
            'legend.borderpad': 0.5,
            
            # 图像质量
            'figure.dpi': 150,
            'savefig.dpi': 300,
            'savefig.bbox': 'tight',
            'savefig.pad_inches': 0.1,
        })


def setup_plot_style():
    """设置全局图表样式"""
    style = PlotStyle()
    style.apply_style()
    return style
